//
//  PersonalDetailViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/5.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "PersonalDetailViewController.h"
#import "PersonalDetailHeaderTableViewCell.h"
#import "BasicMode.h"
#import "BasicInfoHeaderTableViewCell.h"
#import "OtherHeaderTableViewCell.h"
#import "CarTableCellTableViewCell.h"
#import "SellTableViewController.h"
#import "ShareView.h"
#import "ShareWithBackView.h"
#import "ShopUserItem.h"
#import "CarlistCellMode.h"
#import "ShopHeaderModel.h"
#import "ShopTitleModel.h"
#import "BasicPhotoTableViewCell.h"
#import "Address.h"
#import "CarDetailViewController.h"
#import "Puser.h"
#import "UMSocial.h"
#import "ShareMode.h"
#import "MessageDetailTableViewController.h"
@interface PersonalDetailViewController ()<UITableViewDelegate,UITableViewDataSource,otherTableCellClickDelegate,ShareclickDelegate,ShareWithBackToIndexDelegate,UIAlertViewDelegate>
{
    CGFloat srcolly;
}
@property (weak, nonatomic) IBOutlet UITableView *tableview;
@property (nonatomic,strong) NSArray *BasicAarray;
@property (weak, nonatomic) IBOutlet UIButton *attenbtn;

@property (nonatomic,strong) NSMutableArray *dataarray;

@property (nonatomic,strong) NSArray *otherAarray;
@property (nonatomic,strong) ShopUserItem *item;
@property (weak, nonatomic) IBOutlet UIToolbar *toolbar;
@property (nonatomic,strong) Puser *user;
@property (nonatomic,strong) ShareMode *sharemode;
@end

@implementation PersonalDetailViewController
+(instancetype)viewcontroller{
    PersonalDetailViewController *vc=[XHMianStory instantiateViewControllerWithIdentifier:@"pdvc"];
    return vc;
}
-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.y=0;
     [self.attenbtn setTitle:@"加关注" forState:UIControlStateNormal];
     [self.attenbtn setTitle:@"已关注" forState:UIControlStateSelected];
    self.tableview.backgroundColor=bgGarycolor;
    
    self.toolbar.hidden=YES;
    self.tableview.contentInset=UIEdgeInsetsMake(0, 0, 50, 0);
    [self setupRightButton];
    [self getdataFromWeb];
    
    if ([self.tableview respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [self.tableview setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([self.tableview respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [self.tableview setLayoutMargins:UIEdgeInsetsZero];
        
    }

   
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        
        [cell setSeparatorInset:UIEdgeInsetsZero];
        
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        
        [cell setLayoutMargins:UIEdgeInsetsZero];
        
    }
    
    
    
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, XHScreenheight, 30)];
    view.backgroundColor=UIColorWithRGB(238, 238, 238);
    UILabel *lable=[[UILabel alloc]initWithFrame:CGRectMake(16, 0, XHScreenheight, 30)];
    [view addSubview:lable];
    lable.font=[UIFont systemFontOfSize:14];
    lable.textColor=textnormalGary;
    
    if (section==0) {
        view.height=0;
    }else if (section==1){
        lable.text=@"基本信息";
        view.height=30;
    }else{
        lable.text=@"商家其他车源";
        view.height=30;
    }
    return view;
}

//- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
//{
//    // Background color
//    view.tintColor = bgGarycolor;
//    
//    // Text Color
//    
//    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
//    [header.textLabel setTextColor:textnormalGary];
//    header.textLabel.font=[UIFont systemFontOfSize:14];
//    header.textLabel.x=16;
//    // Another way to set the background color
//    // Note: does not preserve gradient effect of original header
//    // header.contentView.backgroundColor = [UIColor blackColor];
//}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 0.1;
    }else{
        return 30;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}
-(void)buttonclick:(NSInteger)ButtonIndex{
    if (ButtonIndex==0) {
        NSLog(@"回到主页");
        
        [self.navigationController popToRootViewControllerAnimated:YES];
        
        
    }else{
        [self share];
    }
}
-(NSMutableArray *)dataarray{
    if ( _dataarray==nil) {
        _dataarray=[NSMutableArray array];
    }
    return  _dataarray;
}
-(void)shareclickWithIndex:(NSInteger)index{
    
  
    
    
     [UMSocialData defaultData].extConfig.wxMessageType = UMSocialWXMessageTypeWeb;
    UIImage  *shareimg;
    UMSocialUrlResource *resource;
    
    if ([self.item.user_ico isEqualToString:@""]||self.item.user_ico==nil) {
        shareimg=[UIImage imageNamed:@"logo210"];
    }else{
        resource=[[UMSocialUrlResource alloc]initWithSnsResourceType:UMSocialUrlResourceTypeImage url:[NSString getImageURLstr:self.item.user_ico]];
    }
    NSDate *nowdate=[NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *str=[dateFormatter stringFromDate:nowdate];
    
    NSString *title=[NSString stringWithFormat:@"%@%@的可售车源【车镇】",self.item.user_truename,str];
     NSString *url=[NSString stringWithFormat:@"%@/modules.php?app=pinfo&shop_id=%@",websitehosturl,self.user_id];
    NSString *content=[self.item.user_intro isEqualToString:@""]||self.item.user_intro==nil?DefalutInfostring:self.item.user_intro;
    
    switch (index) {
        case 0:
        {
            
            
            [UMSocialData defaultData].extConfig.wechatSessionData.title =title;
             [UMSocialData defaultData].extConfig.wechatSessionData.url=url;
            [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatSession] content:content image:shareimg location:nil urlResource:resource presentedController:self completion:^(UMSocialResponseEntity *response){
                if (response.responseCode == UMSResponseCodeSuccess) {
                    NSLog(@"分享成功！");
                }
            }];
        }
            break;
        case 1:
        {
            
           
            [UMSocialData defaultData].extConfig.wechatTimelineData.title =title;
             [UMSocialData defaultData].extConfig.wechatTimelineData.url=url;
            [[UMSocialDataService defaultDataService]  postSNSWithTypes:@[UMShareToWechatTimeline] content:content image:shareimg location:nil urlResource:resource presentedController:self completion:^(UMSocialResponseEntity *response){
                if (response.responseCode == UMSResponseCodeSuccess) {
                    NSLog(@"分享成功！");
                }
            }];
        }
            break;
            
        case 2:
        {
            
            
            
                  }
            break;
            
        default:
            break;
    }
    

    
    
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}

-(void)animationView:(UIView *)view{
    view.alpha=0.0f;
    view.hidden=NO;
    [UIView animateWithDuration:0.5 delay:0.2 options:UIViewAnimationOptionLayoutSubviews animations:^{
        view.alpha=1.0f;
    } completion:^(BOOL finished) {
        
    }];
}

-(void)share{
    NSArray *titlearray=@[@"微信",@"朋友圈",@"短信"];
    UIImage *weixin=[UIImage imageNamed:@"weixin"];
    UIImage *pengyou=[UIImage imageNamed:@"liulan"];
    UIImage *sms=[UIImage imageNamed:@"duanxin"];
    NSArray *icon=@[weixin,pengyou,sms];
    ShareView *share=[[ShareView alloc]initWithTitle:titlearray andIcons:icon delegate:self];
    [share show];
}
-(void)getdataFromWeb{
   
    
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"user_id"]=self.user_id;
    
    params[@"action"]=@"info";
    params[@"car_num"]=@"3";
    int power=[self.user.power intValue];
    if (power<5) {
        params[@"self_id"]=self.user.user_id;
        params[@"type"]=@"0";
        if ([self.user.user_id integerValue]!=[self.user_id integerValue]) {
            [self animationView:self.toolbar];
        }
    }else{
        if (power ==8) {
            params[@"self_id"]=self.user.parent_id;
            params[@"type"]=@"2";
        }else{
            params[@"type"]=@"1";
            params[@"self_id"]=self.user.com_id;
        }
        [self animationView:self.toolbar];
    }
    
    [PostUitls Post:lookforcar parameters:params success:^(id response) {
        
        NSDictionary *dict=response;
       
        
        ShopUserItem *item=[ShopUserItem shopwithDict:dict[@"data"]];
            self.item=item;
            [self setupData];
        
        
    } failure:^(NSError *error) {
        
    }];
    
}

-(void)setupData{
    
   
    
    if ([self.item.atten integerValue]==0) {
        self.attenbtn.selected=NO;
    }else{
        self.attenbtn.selected=YES;
    }
    ShopHeaderModel *headmode=[[ShopHeaderModel alloc]init];
    
    headmode.headpic=self.item.user_ico;
    headmode.headname=self.item.user_truename;
    headmode.shoptype=@"个人商铺";
    [self.dataarray addObject:@[headmode]];
     
    BasicMode *phone=[[BasicMode alloc]init];
    phone.name=@"电话";
    phone.detail=self.item.user_mobile;
    phone.isImageMode=NO;
    
    
    BasicMode *personinfo=[[BasicMode alloc]init];
    personinfo.name=@"个人简介";
    personinfo.detail=[self.item.user_intro isEqualToString:@""]||self.item.user_intro==nil?@"暂未填写":self.item.user_intro;
    personinfo.isImageMode=NO;
    personinfo.ismultlesLines=YES;
    BasicMode *qq=[[BasicMode alloc]init];
    qq.name=@"QQ";
    qq.detail=self.item.user_qq?self.item.user_qq:@"暂无";
    qq.isImageMode=NO;
    BasicMode *weichat=[[BasicMode alloc]init];
    weichat.name=@"微信";
    weichat.detail=self.item.user_weixin?self.item.user_weixin:@"暂无";
    weichat.isImageMode=NO;
    
    BasicMode *company=[[BasicMode alloc]init];
    company.name=@"所属公司";
    company.detail=[self.item.user_skype isEqualToString:@""]?@"暂无":self.item.user_skype;
    company.isNUll=[self.item.user_skype isEqualToString:@""]?YES:NO;
    company.isImageMode=NO;
    
    BasicMode *address=[[BasicMode alloc]init];
    address.name=@"联系地址";
    
    if ([self.item.user_province integerValue]!=0) {
        Address *pro=[Address getAdressbyID:self.item.user_province];
        Address *city=[Address getAdressbyID:self.item.user_city];
        Address *dist=[Address getAdressbyID:self.item.user_district];
         address.detail=[NSString stringWithFormat:@"%@%@%@",pro.area_name,city.area_name,dist.area_name];
    }else{
        address.detail=@"暂无联系地址";
        address.isNUll=YES;
    }
    
   
    
   
    address.isImageMode=NO;

    BasicMode *img=[[BasicMode alloc]init];
    img.name=@"展示照片";
    img.isImageMode=YES;
    img.isNUll=self.item.show_pics.count==0?YES:NO;
    img.detail=@"暂无";
    img.imgsarray=self.item.show_pics;
    self.BasicAarray=@[phone,personinfo,qq,weichat,company,address,img];
    [self.dataarray addObject:self.BasicAarray];
    ShopTitleModel *mode=[[ShopTitleModel alloc]init];
    
    
    NSMutableArray *array=[NSMutableArray array];
    [array addObject:mode];
    for (CarDetailmodel *detail in self.item.my_car) {
        CarlistCellMode *cellmode=[[CarlistCellMode alloc]init];
        detail.shop_name=self.item.user_truename;
        cellmode.cardmode=detail;
        [array addObject:cellmode];
    }
    
    self.otherAarray=array;
    [self.dataarray addObject:self.otherAarray];
    [self.tableview reloadData];
    
}
- (IBAction)bottomclick:(UIButton *)sender {
    switch (sender.tag) {
        case 0:
            [self guanzhu:sender];
            break;
        case 1:
            [self sendmessage];
            break;
        case 2:
            [self tellphone];
            break;
        default:
            break;
    }
    
}
-(void)guanzhu:(UIButton *)sender{
    
     MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    hud.labelText=@"正在操作";
    hud.margin = 10.f;

    hud.removeFromSuperViewOnHide = YES;
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    
    if (sender.selected) {
        params[@"action"]=@"cansol";
        params[@"shop_id"]=self.user_id;
        params[@"type"]=@"0";
        if ([self.user.power integerValue]==1) {
            params[@"user_id"]=self.user.user_id;
        }else{
            if ([self.user.power integerValue]==5) {
                params[@"com_id"]=self.user.com_id;
            }else if ([self.user.power integerValue]==8){
                params[@"parent_id"]=self.user.parent_id;
            }
        }

    }else{
    params[@"action"]=@"add_faver";
    params[@"shop_id"]=self.user_id;
    params[@"type"]=@"0";
    if ([self.user.power integerValue]==1) {
         params[@"user_id"]=self.user.user_id;
    }else{
        if ([self.user.power integerValue]==5) {
            params[@"com_id"]=self.user.com_id;
        }else if ([self.user.power integerValue]==8){
            params[@"parent_id"]=self.user.parent_id;
        }
    }
    
    }
    [PostUitls Post:addgzurl parameters:params success:^(id response) {
        NSDictionary *dict=response;
        hud.mode=MBProgressHUDModeText;
        NSNumber *state=dict[@"state"];
        if ([state integerValue]==400) {
            sender.selected=!sender.selected;
        }
        hud.labelText=dict[@"msg"];
        
        
        [hud hide:YES afterDelay:1];
        
    } failure:^(NSError *error) {
        hud.labelText=@"网络错误";
        
        
        [hud hide:YES afterDelay:1];
    }];
    
}
-(void)sendmessage{
    
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[MessageDetailTableViewController class]]) {
            [self.navigationController popToViewController:vc animated:YES];
            return;
        }
    }
    
    MessageDetailTableViewController *mvc=[[MessageDetailTableViewController alloc]init];
    mvc.toico=self.item.user_ico;
    mvc.toid=self.user_id;
    mvc.totype=@"1";
    mvc.navigationItem.title=self.item.user_truename;
    
    [self.navigationController pushViewController:mvc animated:YES];
}


-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==0) {
        return;
    }else{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",self.item.user_mobile]]];
        
    }
   
    
}

-(void)tellphone{
    UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"确定拨打此电话" message:self.item.user_mobile delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}
-(void)setupRightButton{
    ShareWithBackView *shareandback=[ShareWithBackView sharewithback];
    shareandback.delegate=self;
    UIBarButtonItem *rightitem=[[UIBarButtonItem alloc] initWithCustomView:shareandback];
    self.navigationItem.rightBarButtonItem=rightitem;
    self.automaticallyAdjustsScrollViewInsets=NO;
}



-(void)setupNav:(BOOL)isTOP{
    if (isTOP) {
        UIImage *clearimage= [UIImage imageNamed:@"v_line"];
        [self.navigationController.navigationBar setBackgroundImage:clearimage forBarMetrics:UIBarMetricsDefault];
        [self.navigationController.navigationBar setTranslucent:YES];
        [self.navigationController.navigationBar setShadowImage:clearimage];
        [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    }else{
        UIImage *detail= [UIImage imageNamed:@"detail_navbg"];
        [self.navigationController.navigationBar setBackgroundImage:detail forBarMetrics:UIBarMetricsDefault];
        [self.navigationController.navigationBar setTranslucent:YES];
       
        [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];

    }
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self setupSollNav:srcolly];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGPoint offset = scrollView.contentOffset;
    float y = offset.y;
     srcolly=y;
    [self setupSollNav:y];
    
}
-(void)setupSollNav:(CGFloat )y{
   
    float reload_distance = -20;
   
    if(y > 91 + reload_distance) {
        //距离到底 20 像素
        NSLog(@"改变状态栏颜色");
        
        [self setupNav:NO];
    }else{
        [self setupNav:YES];
    }
   

}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataarray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *array=self.dataarray[section];
    
    return array.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array=self.dataarray[indexPath.section];
    if (indexPath.section!=2) {
        
        BasicMode *mode=array[indexPath.row];
        if ([mode isKindOfClass:[ShopHeaderModel class]]) {
            PersonalDetailHeaderTableViewCell *cell=[PersonalDetailHeaderTableViewCell cellWithTable:tableView];
            ShopHeaderModel *headermode=mode;
            cell.headermode=headermode;
            return cell;
        }else{
            if (mode.isImageMode &&!mode.isNUll) {
                BasicPhotoTableViewCell *cell=[BasicPhotoTableViewCell cellWithTableView:tableView];
                cell.imgarray=mode.imgsarray;
                cell.title.text=@"展示照片";
                return cell;
                
            }else{
                UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"basiccell"];
                if (cell==nil) {
                    cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"basiccell"];
                    cell.textLabel.textColor=UIColorWithRGB(178, 178, 178);
                    if (mode.isNUll) {
                        cell.detailTextLabel.textColor=UIColorWithRGB(211 , 211, 211);
                        
                    }else{
                        cell.detailTextLabel.textColor=UIColorWithRGB(112, 112, 112);
                    }
                    
                }
                cell.textLabel.text=mode.name;
                cell.textLabel.font=[UIFont systemFontOfSize:15];
                cell.detailTextLabel.text=mode.detail;
                cell.detailTextLabel.font=[UIFont systemFontOfSize:13];
                if (mode.ismultlesLines) {
                    cell.detailTextLabel.numberOfLines=0;
                }else{
                    cell.detailTextLabel.numberOfLines=1;
                }
                return cell;
            }
        }
        
    }else {
        if (indexPath.row==0) {
            OtherHeaderTableViewCell *cell=[OtherHeaderTableViewCell cellWithTableView:tableView];
            cell.tableclickdelegate=self;
            return cell;
        }else{
            CarTableCellTableViewCell *cell=[CarTableCellTableViewCell cellWithTableView:tableView];
            CarlistCellMode *cellmode=array[indexPath.row];
            cell.carcellmode=cellmode;
            return cell;
        }
        
        
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array=self.dataarray[indexPath.section];
    if (indexPath.section!=2) {
        BasicMode *mode=array[indexPath.row];
        if (mode.blcok) {
            mode.blcok();
        }
    }else{
        CarlistCellMode *cellmode=array[indexPath.row];
        if (indexPath.row==0) {
            return;
        }
        CarDetailViewController *vc=[CarDetailViewController viewcontroller];
        vc.ID=cellmode.cardmode.ID;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(void)click:(NSInteger)tag{
    NSLog(@"%ld",tag);
    if (tag==0) {
        UIImage  *shareimg;
        UMSocialUrlResource *resource;
        
        if ([self.item.user_ico isEqualToString:@""]||self.item.user_ico==nil) {
            shareimg=[UIImage imageNamed:@"logo210"];
        }else{
            resource=[[UMSocialUrlResource alloc]initWithSnsResourceType:UMSocialUrlResourceTypeImage url:[NSString getImageURLstr:self.item.user_ico]];
        }        NSDate *nowdate=[NSDate date];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        NSString *str=[dateFormatter stringFromDate:nowdate];
        
        NSString *title=[NSString stringWithFormat:@"%@%@的可售车源【车镇】",self.item.user_truename,str];
        ShareMode *mode=[[ShareMode alloc]init];
        mode.sharetitle=title;
        mode.sharecontent=[self.item.user_intro isEqualToString:@""]||self.item.user_intro==nil?DefalutInfostring:self.item.user_intro;
        mode.logo=shareimg;
        mode.resource=resource;
        mode.url=[NSString stringWithFormat:@"%@/modules.php?app=sale_car&shop_id=%@&shop_name=%@&sale_attr=2",websitehosturl,self.user_id,self.item.user_truename];
        SellTableViewController *stvc=[XHMianStory instantiateViewControllerWithIdentifier:@"sell"];
        stvc.userid=self.user_id;
        stvc.sharemode=mode;
        [self.navigationController pushViewController:stvc animated:YES];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSArray *array=self.dataarray[indexPath.section];
    if (indexPath.section==0) {
        return 180;
    }else if
        
    (indexPath.section==2&&indexPath.row!=0)
    {
        CarlistCellMode *cell=array[indexPath.row];
        return cell.rowheight;
    }
    else{
        BasicMode *mode=array[indexPath.row];
        
        if (mode.ismultlesLines) {
           return mode.rowheight;
        }else if (mode.isImageMode){
            return 80;
        }
        else{
            return 44;
        }
        
        
    }
   
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
